package edu.cn.neusoft.dm.showweb.service

import edu.cn.neusoft.dm.showweb.bean.db.SysLogin
import edu.cn.neusoft.dm.showweb.bean.db.SysLoginExample
import edu.cn.neusoft.dm.showweb.bean.db.UserInfoExample
import edu.cn.neusoft.dm.showweb.bean.dealform.LOGIN_FAILED
import edu.cn.neusoft.dm.showweb.bean.dealform.user.login.LoginRequest
import edu.cn.neusoft.dm.showweb.bean.dealform.user.login.LoginResponse
import edu.cn.neusoft.dm.showweb.mapper.SysLoginMapper
import edu.cn.neusoft.dm.showweb.mapper.UserInfoMapper
import edu.cn.neusoft.dm.showweb.util.tokenmaker
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.util.DigestUtils
import java.util.*

/**
 * author:纷羽
 * create at 2018/7/13
 */
@Service
class UserService {

    @Autowired
    private lateinit var userInfoMapper: UserInfoMapper
    @Autowired
    private lateinit var sysLoginMapper: SysLoginMapper

    fun login(request: LoginRequest): LoginResponse {
        val example = UserInfoExample()
        example.createCriteria().andUserNameEqualTo(request.username)
        val userlist = userInfoMapper.selectByExample(example)
        if (userlist.isNotEmpty()) {
            if (userlist[0].userPass == String(DigestUtils.md5Digest(request.userpass.toByteArray()))) {
                var token = tokenmaker()
                var exampleoftoken = SysLoginExample()
                exampleoftoken.createCriteria().andLoginTokenEqualTo(token).andEffOverTimeGreaterThan(Date())
                while (sysLoginMapper.selectByExample(exampleoftoken).isNotEmpty()) {
                    token = tokenmaker()
                    exampleoftoken = SysLoginExample()
                    exampleoftoken.createCriteria().andLoginTokenEqualTo(token).andEffOverTimeGreaterThan(Date())
                }
                val sysLogin = SysLogin()
                sysLogin.effOverTime = Date(Date().time + (5 * 60 * 1000))
                sysLogin.loginToken = token
                sysLogin.loginTime = Date()
                sysLogin.userId = userlist[0].userId
                sysLoginMapper.insertSelective(sysLogin)
                val response = LoginResponse()
                response.identify = userlist[0].identify
                response.token = token
                return response
            }
        }
        return LoginResponse(LOGIN_FAILED, "账号或密码错误")
    }


}